#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define SIZE 1024
#define FLUSH_LINE 1
const int _size = 1024;
struct IO_FILE
{
  int fileno;

  char buffer[1024];
  int size;
  int capacity;
  int _flush;
};
typedef struct IO_FILE mFILE;

mFILE* mopen(const char* path,const char* way)
{
  mFILE* fp = (mFILE*)malloc(sizeof(mFILE));
  if(fp==NULL)
    return NULL;
  fp->size = 0;
  fp->capacity = _size;
  fp->_flush = FLUSH_LINE;
  if(strcmp(way,"w")==0)
  {
    int fd = open(path,O_CREAT|O_WRONLY|O_TRUNC,0666);
    fp->fileno = fd;
  }
  else if(strcmp(way,"r")==0)
  {
    int fd = open(path,O_RDONLY);
    fp->fileno = fd;
  }
  else if(strcmp(way,"a")==0)
  {
    int fd = open(path,O_CREAT|O_WRONLY|O_APPEND,0666);
    fp->fileno = fd;
  }
  return fp;
}
void mfflush(mFILE* fp)
{
  printf("%s",fp->buffer);
  fp->size = 0;
}
int mprintf(const char* s,int num,mFILE* fp)
{
  memcpy(fp->buffer+fp->size,s,num);
  if(fp->_flush==FLUSH_LINE&&s[num]=='\n')
  {
    //printf("%s",fp->cache);
    mfflush(fp);
    fp->size = 0;
  }
  else
  {
    fp->size+=num;
  }
  return num;
}
void mclose(mFILE* fp)
{

  close(fp->fileno);

}
